package com.unitd.frame.springweb.controller.aop;

import com.unitd.frame.comm.exception.UnLoginException;
import com.unitd.frame.comm.exception.UnitdBaseException;
import com.unitd.frame.springweb.controller.result.AjaxResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @desc Controller控制器的AOP处理类
 * @filename ControllerAop.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/12/25
 */
public class ControllerAop {
	private static final Logger logger = LoggerFactory.getLogger(ControllerAop.class);

	/**
	 * @desc AOP切面切入方法
	 * @param point 切点
	 * @return Object
	 */
	public Object handlerControllerMethod(ProceedingJoinPoint point) {
		long startTime = System.currentTimeMillis();
		AjaxResult result;

		try {
			result = (AjaxResult) point.proceed();
			logger.info(point.getSignature() + "use time:" + (System.currentTimeMillis() - startTime));
		} catch (Throwable e) {
			result = handlerException(point, e);
		}

		return result;
	}

	/**
	 * @desc 处理异常
	 * @param point 切点
	 * @param e 异常对象
	 * @return 通用Restful对象
	 */
	private AjaxResult handlerException(ProceedingJoinPoint point, Throwable e) {
		AjaxResult result = new AjaxResult();
		result.setSuccess(false);

		// 未登录
		if (e instanceof UnLoginException) {
			result.setCode(AjaxResult.NO_LOGIN);
			result.setMsg(e.getLocalizedMessage());
		} else if (e instanceof UnitdBaseException) {
			// 自定义异常
			result.setCode(AjaxResult.FAIL);
			result.setMsg(e.getLocalizedMessage());
		} else {
			// 未知异常是应该重点关注的,这里可以做其他操作,如通知邮件,单独写到某个文件等等
			logger.error(point.getSignature() + " error ", e);
			result.setCode(AjaxResult.UNKNOWN_EXCEPTION);
			result.setMsg(e.toString());
		}
		return result;
	}
}